<template>
  <div class="contentClass">
    <el-form :model="queryForm"
             label-width="100px">

      <el-row class="request-header dm-form">
        <el-col :lg="{span:3}"
                :md="{span:3}"
                :sm="{span:5}"
                :xs="{span:24}">
          <el-button type="primary"
                     @click="_handleOperate({},'add')">
            新增业务
          </el-button>
        </el-col>

        <el-col :lg="{span:12,offset:4}"
                :md="{span:12,offset:3}"
                :sm="{span:10,offset:1}"
                :xs="{span:24}"
                class="align-right">
          <el-form-item prop="tpl_name"
                        label="业务名称">
            <el-input v-model="queryForm.tpl_name"
                      placeholder="输入搜索关键字"
                      clearable></el-input>
          </el-form-item>

        </el-col>
        <el-col :lg="{span:4,offset:1}"
                :md="{span:6}"
                :sm="{span:8}"
                :xs="{span:24}"
                class="flex-end">
          <el-button type="primary"
                     @click="_searchTable">搜索</el-button>
          <el-button @click="_resetForm">重置</el-button>
        </el-col>
      </el-row>

    </el-form>

    <el-table :data="tableData"
              height="600px">
      <el-table-column width="60"
                       label="序号"
                       fixed>
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column prop="tpl_name"
                       label="业务名称"></el-table-column>
      <el-table-column prop="business_type_name"
                       label="类型">
        <!-- <template slot-scope="scope">
          <span v-if="scope.row.business_type==1">检查对象模式</span>
          <span v-if="scope.row.business_type==2">独立模式</span>
          <span v-if="scope.row.business_type==3">流程模式</span>
          <span v-if="scope.row.business_type==4">数据源流程模式</span>
          <span v-if="scope.row.business_type==10">监控台模式</span>
        </template> -->
      </el-table-column>
      <el-table-column prop="updated_at"
                       label="更新时间"></el-table-column>
      <el-table-column prop="run_status"
                       label="运行状况">
        <!--        <template slot-scope="scope">-->
        <!--          <span v-if="scope.row.run_status==0">异常</span>-->
        <!--          <span v-if="scope.row.run_status==1">检查对象模式</span>-->
        <!--        </template>-->
      </el-table-column>

      <el-table-column label="操作"
                       width="200"
                       fixed="right">
        <template slot-scope="scope">
          <el-button type="text"
                     @click="publishApp(scope.row)">发布</el-button>

          <el-button @click="_handleOperate(scope.row, 'detail')"
                     type="text">
            配置
          </el-button>
          <el-button @click="_handleOperate(scope.row, 'edit')"
                     type="text">
            修改
          </el-button>
          <el-button @click="_handleOperate(scope.row, 'delete')"
                     type="text">
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-pagination class="flexCenter"
                   align="center"
                   :current-page="queryForm.page"
                   :page-sizes="[10, 20, 50, 100]"
                   :page-size="queryForm.page_size"
                   :total="queryForm.total_count"
                   layout="total, sizes, prev, pager, next, jumper"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"></el-pagination>

    <el-dialog :title="dialogType==='add'?'新增业务':'修改业务'"
               @close="_closeDialog"
               width="40%"
               :visible.sync="dialogBusinessFlag">
      <el-form :model="dialogForm"
               ref="ruleForm"
               :rules="formRules"
               label-width="120px">
        <el-form-item label="业务名称"
                      prop="tpl_name">
          <el-input v-model="dialogForm.tpl_name"
                    placeholder="请输入业务名称"
                    autocomplete="off"></el-input>
        </el-form-item>
        <!-- 检查项业务-类型选择 -->
        <el-form-item label="类型"
                      v-if="businessType==='check'">
          <el-select v-model="dialogForm.business_type"
                     placeholder="请选择业务类型">
            <el-option v-for="(item,i) in businessTypeArr"
                       :key="i"
                       :label="item.name"
                       :value="item.value"></el-option>
          </el-select>
          <p style="color: #ccc;">内部节点单独存在，对象互不干扰关联</p>
        </el-form-item>
        <!-- 监控台业务-类型选择 -->
        <el-form-item label="类型"
                      prop="app_sort_no"
                      v-if="businessType==='monitor'">
          <el-select v-model="dialogForm.app_sort"
                     @change="chooseSortNo"
                     placeholder="请选择应用分类">
            <el-option v-for="item in appSortCode"
                       :key="item.code_id"
                       :label="item.name"
                       :value="item.value"></el-option>
          </el-select>
          <el-select v-model="dialogForm.app_sort_no"
                     placeholder="请选择应用编号">
            <el-option v-for="item in appSortNoList"
                       :key="item.no"
                       :label="item.name"
                       :value="item.no">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="logo"
                      prop="logo">
          <div class="choose-icon">
            <el-input placeholder="请选择logo"
                      v-model="dialogForm.logo"
                      disabled></el-input>
            <el-button @click="chooseIconDialogVisible=true"
                       type="primary">选择logo</el-button>
          </div>

        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="dialogForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogBusinessFlag = false">取 消</el-button>
        <el-button type="primary"
                   @click="dialogBusinessOK">确 定</el-button>
      </div>
    </el-dialog>
    <ChooseIconDialog :dialogVisible.sync="chooseIconDialogVisible"
                      @callback="chooseIconCb"></ChooseIconDialog>
    <PublishAppDialog :dialogVisible.sync="publishAppDialogVisible"
                      :businessType="businessType"
                      :dialogForm="publishAppDialogForm"
                      @callback="publishAppCb"></PublishAppDialog>
    <ExternialLinkDialog :dialogExternialLink.sync="dialogExternialLink"
                         v-if="dialogExternialLink"
                         :objRow.sync="objRow"></ExternialLinkDialog>
  </div>
</template>

<script>
import PublishAppDialog from './components/PublishAppDialog'
import { UploadFileApi } from '@/services/UserPermission'
import { CommonCheckApi } from "../../../services/SystemSetting";
import ChooseIconDialog from './components/ChooseIconDialog'
import { standardCodeApi } from '@/services/StandardCode'
import ExternialLinkDialog from './components/ExternialLinkDialog';//外部链接模式
export default {
  components: {
    PublishAppDialog, ChooseIconDialog,
    ExternialLinkDialog,
  },
  data () {
    return {
      objRow: {},//外部链接的对象
      dialogExternialLink: false,//外部链接模式
      businessTypeArr: [],//业务类型
      dialogBusinessFlag: false,
      dialogType: 'add',
      dialogForm: {
        tpl_name: '',
        business_type: '2',
        app_sort: '',
        app_sort_no: '',
        remark: '',
        logo: ''
      },

      queryForm: {
        tpl_name: '',
        is_page: 1,
        page: 1,
        page_size: 10,
        total_count: 0,
        business_type: ''
      },
      formRules: {
        tpl_name: [
          { required: true, message: '请输入业务名称', trigger: 'blur' }
        ],
        logo: [
          { required: true, message: '请选择logo', trigger: 'blur' }
        ],
        app_sort_no: [
          { required: true, message: '请选择应用编号', trigger: 'blur' }
        ]
      },
      tableData: [],
      // 发布app弹框是否可见
      publishAppDialogVisible: false,
      // 发布app弹框数据对象
      publishAppDialogForm: {},
      // 版本图片列表
      versionPicList: [],
      // 选择图标弹框是否可见
      chooseIconDialogVisible: false,
      // 应用分类标准码
      appSortCode: [],
      appSortMap: new Map(),
      // 应用分类下的应用编号
      appSortNoList: [],
      businessTypeMap: new Map(),//业务类型
    };
  },
  props: {
    // 业务类型，区分监控台业务及检查项业务
    businessType: {
      type: String,
      default: 'check'
    }
  },
  async mounted () {
    let checkItemBusinessType = JSON.parse(window.localStorage.getItem('checkItemBusinessType'));//业务类型
    console.log('业务类型checkItemBusinessType=', checkItemBusinessType);//业务类型
    if (checkItemBusinessType) {//判断业务类型是否存在
      this.businessTypeArr = checkItemBusinessType;
      await this.setBusinessType();//设置
    } else {
      await this.getCheckItemBusinessType();//业务类型标准码
    };
    let appSortLocal = window.localStorage.getItem('appSortCode')
    if (appSortLocal) {
      this.appSortCode = JSON.parse(appSortLocal)
      this.appSortCode.map((item) => {
        this.appSortMap.set(item.value, item)
      })
    } else {
      await this.getAppSortCode()
    }
    this._getList()
  },
  methods: {
    //设置
    setBusinessType () {
      if (this.businessTypeArr.length > 0) {
        this.businessTypeArr.map((item) => {
          this.businessTypeMap.set(item.value, item);
        });
      };
      console.log('验证 businessTypeMap=', this.businessTypeMap, this.businessTypeArr);
    },
    //获取检查项类型
    getCheckItemBusinessType () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'checkItemBusinessType'//业务类型
        }
      }).then((res) => {
        if (res.data) {
          let list = res.data.list;
          this.businessTypeArr = [];//业务类型
          this.businessTypeArr = list;
          if (list.length > 0) {
            this.setBusinessType();//设置
          }
          window.localStorage.setItem('checkItemBusinessType', JSON.stringify(list));//业务类型
          console.log('业务类型res=', res)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 选择应用分类
    chooseSortNo () {
      let appSort = this.appSortMap.get(this.dialogForm.app_sort) || {}
      this.dialogForm.app_sort_no = ''
      let content = appSort.content1
      content = JSON.parse(content) || {}
      this.appSortNoList = content.data || []

    },
    // 获取应用分类标准码
    getAppSortCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'applicaitonSort'
        }
      }).then(res => {
        if (res.code === 0) {
          this.appSortCode = res.data.list
          this.appSortCode.map((item) => {
            this.appSortMap.set(item.value, item)
          })
          window.localStorage.setItem('appSortCode', JSON.stringify(res.data.list));
        }
      })
    },
    // 发布app
    publishApp (data) {
      this.publishAppDialogForm = data
      this.publishAppDialogVisible = true
    },
    // 发布app弹框回调
    publishAppCb (data) {
      this.publishAppDialogForm = {}
    },
    chooseIconCb (data) {
      this.dialogForm.logo = data.name
    },
    dialogBusinessOK () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.businessType === 'monitor') {
            this.dialogForm.business_type = 10
          };
          let type = this.dialogForm.business_type;
          let name = ''
          if (type == 2) {
            name = '独立模式'
          } else if (type == 3) {
            name = '流程模式'
          } else if (type == 4) {
            name = '数据源流程模式'
          } else if (type == 10) {
            name = '监控台模式'
          } else if (type == 5) {
            name = '外部链接模式'
          }
          if (this.dialogType === 'add') {
            CommonCheckApi.create_businessAPI({
              data: {
                ...this.dialogForm,
                business_type_name: name
              }
            }).then(res => {
              if (res.code === 0) {
                this.$message.success('添加成功')
                this.dialogBusinessFlag = false
                this._getList()
              }

            })
          } else {
            CommonCheckApi.update_businessAPI({
              data: this.dialogForm
            }).then(res => {
              if (res.code === 0) {
                this.$message.success('修改成功')
                this.dialogBusinessFlag = false
                this._getList()
              }

            })

          }
        }
      })


    },
    handleSizeChange (val) {
      this.queryForm.page_size = val
      this._getList()
    },
    handleCurrentChange (val) {
      this.queryForm.page = val
      this._getList()
    },

    _closeDialog () {
      this.dialogForm = this.$options.data().dialogForm
    },
    _getList () {
      if (this.businessType === 'monitor') {
        this.queryForm.business_type = '10'
      } else {
        this.queryForm.business_type = ''
      }
      CommonCheckApi.getbusiness_listAPI({
        params: this.queryForm
      }).then(res => {
        let data = res.data
        data.list.forEach(v => {
          if (v.updated_at == null) {
            v.updated_at = ''
          }
        })
        this.tableData = data.list
        this.queryForm.page = data.page
        this.queryForm.page_size = data.page_size
        this.queryForm.total_count = data.total_count
      })
    },
    _searchTable () {
      this.queryForm.page = 1;
      this._getList();
    },
    _handleOperate (row, type) {
      this.dialogType = type
      if (type == 'add') {
        this.dialogBusinessFlag = true
      }
      if (type == "edit") {
        this.dialogBusinessFlag = true
        this.dialogForm = { ...row }
      }
      if (type == "detail") {
        if (row.business_type == 5) {//外部链接模式执行这一步
          this.objRow = Object.assign({}, row);//拷贝
          this.dialogExternialLink = true;//外部链接弹框
        } else {//非链接模式执行这一步
          this.$router.push({
            path: '/checkBusinessConfigDetail',
            query: {
              id: row.check_tpl_id,
            }
          })
        }
      }
      if (type == 'delete') {
        this.$confirm('确定要删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          CommonCheckApi.delete_businessAPI({
            data: {
              check_tpl_id: row.check_tpl_id
            }
          }).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功')
              this._getList()
            }
          })
        })

      }

    },

    _resetForm () {
      this.queryForm = this.$options.data().queryForm;
      this._searchTable();
    },
  },
};
</script>

<style scoped lang="scss">
.contentClass {
  padding: 20px;
  .el-pagination {
    margin-top: 20px;
  }
  .choose-icon {
    display: flex;
    .el-input {
      margin-right: 20px;
    }
  }
}
</style>
